<template>
    <div class="jianzhan-content">
        <Crumb name="Stock In"/>
        <div class="content">
            <el-button size="small" @click="openAdd" type="primary">Add Stock In</el-button>
            <Search>
                <el-input v-model="key" class="input" size="small" prefix-icon="el-icon-search"
                          placeholder="Search by Stock in number"/>
            </Search>
            <div class="table-wrapper">
                <el-table border
                          stripe
                          row-key="id"
                          @expand-change="getPartDetail"
                          :data="stockList.slice((pageNum-1)*pageSize,pageNum*pageSize)"
                >
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-table  :data="props.row.partList" border>
                                <el-table-column
                                        prop="partsNumber"
                                        label="Part No"
                                        width="180">
                                </el-table-column>
                                <el-table-column
                                        prop="denomination"
                                        label="Description"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="designation"
                                        label="Description"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="partsQuantity"
                                        label="Qty"
                                >
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column label="Stock in No" prop="stockInNum"/>
                    <el-table-column label="Exporter" prop="exporterDesc"/>
                    <el-table-column label="Export Number" prop="exportNum"/>
                    <el-table-column label="Ship Number" prop="shipNumber"/>
                    <el-table-column label="Stock in Date" prop="stockInDateStr"/>
                    <el-table-column label="Detail">
                        <template slot-scope="stock">
                            <el-button  type="primary" size="small" @click="showDetail(stock.row)">Details</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>
        <el-dialog title="Stock In" :visible.sync="dialogVisible" width="80%">
            <el-form :model="stock" ref="stock" :rules="rule" label-width="150px">
                <div class="flex">
                    <div class="flex-content">
                        <el-form-item label="Usage" prop="exploit">
                            <el-select v-model="stock.exploit" size="small" class="input">
                                <el-option label="Consignment" :value=0></el-option>
                                <el-option label="Self Purchase" :value=1></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Export Number" prop="exportNum">
                            <el-input v-model="stock.exportNum" size="small" class="input"></el-input>
                        </el-form-item>
                        <el-form-item label="Stock in date" prop="stockInDateStr">
                            <el-date-picker v-model="stock.stockInDateStr" value-format="yyyy-MM-dd" size="small" class="input"/>
                        </el-form-item>
                        <el-form-item label="Warehouse" prop="warehouse">
                            <el-select v-model="stock.warehouse" placeholder="warehouse" size="small" class="input">
                                <el-option
                                        v-for="item in warehouseList"
                                        :key="item.id"
                                        :label="item.warehouseName"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex-content">
                        <el-form-item label="Exporter" prop="exporter">
                            <el-select v-model="stock.exporter" size="small" class="input" placeholder="Exporter">
                                <el-option label="Inline" :value=0></el-option>
                                <el-option label="Shacman" :value=1></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Ship Number" prop="shipNumber">
                            <el-input v-model="shipNumber1" placeholder="Ship Number" size="small" style="width: 40%"></el-input>
                            <el-input v-model="shipNumber2" placeholder="Ship Number" size="small" style="width: 20%"></el-input>
                        </el-form-item>
                        <el-form-item label="Stock in number">
                            <el-input v-model="stockinNum" disabled  size="small" class="input"/>
                        </el-form-item>
                        <el-form-item label="Box Number" prop="totalBoxes">
                            <el-input v-model="stock.totalBoxes" placeholder="Box Number" size="small" class="input"></el-input>
                        </el-form-item>

                    </div>
                </div>
                <div style="text-align: left;margin-bottom: 10px;">
                    <el-button size="small" type="primary" @click="dbVisible = true">Add Parts</el-button>
                    <label class="label" for="partExcel">Upload Excel</label>
                    <input type="file" id="partExcel" ref="file"
                           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                           size="small" @change="fileChange" style="display: none"/>
                </div>
                <Data-Base @deleteItem="deleteItem" :partList="partList"/>
            </el-form>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button @click="saveForm" v-if="!(stock.saveOrConfirm === 1)" type="warning" v-show="!stock.saveOrConfirm">Save</el-button>
                        <el-button type="primary" v-if="!(stock.saveOrConfirm === 1)" @click="submitForm" v-show="!(stock.saveOrConfirm === 1)">Confirm</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="New part"
                :visible.sync="notExistVisible"
                width="90%"
                >
            <el-table
                    :data="notExist"
                    border
                    stripe
                    style="width: 100%">
                <el-table-column
                    type="index"
                    label="No"
                 >
                </el-table-column>
                <el-table-column
                        prop="partsNum"
                        label="part number"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="denomination"
                        label="description"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="designation"
                        label="description">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="notExistVisible = false">Confirm</el-button>
            <el-button @click="insertDataBase">Insert Into Data Base</el-button>
          </span>
        </el-dialog>
        <el-dialog
                title="Progress"
                :visible="progress"
                width="50%"
               >
            <span>{{current}}／{{notExist.length}}</span>
            <el-progress :percentage="(current/notExist.length)*100"/>
        </el-dialog>
        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible"/>
    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import Search from '../../components/common/search'
    import PartItem from '../../components/part/sparePartItem'
    import DataBase from '../../components/part/spDataBase'
    import {getStockInList, stockIn, getStockInDetail, saveStockIn, getStockInRecord} from "../../api/service";
    import {getWarehouseList} from "../../api/warehouse";
    import {addPart} from "../../api";
    import {mapMutations} from 'vuex'
    import {upLoadFile} from "../../api";
    import {mapActions} from 'vuex';
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import spMixins from '../../util/spMixins'

    export default {
        name: "stock-out",
        mixins: [mixins, spMixins],
        data() {
            return {
                shipNumber1:'',
                shipNumber2:'',
                list: [],
                workNoList: [],
                notExist:[],
                rule:{
                    stockInDateStr:[{required:true}],
                    exploit:[{required:true}],
                    exporter:[{required:true}],
                    exportNum:[{required:true}],
                    shipNumber:[{required:true}],
                    totalBoxes:[{required:true}],
                    warehouse:[{required:true}]
                },
                warehouseList:[],
                stock: {
                    stockInNum:'',
                    stockInDateStr:'',
                    stockOutDetails: [],
                    exploit:'',
                    exporter:'',
                    exportNum:'',
                    warehouse:'',
                    shipNumber:'',
                    totalBoxes:''
                },
                key: '',
                dialogVisible: false,
                notExistVisible:false,
                current:0,
                progress:false,
                editable:true
            }
        },
        computed: {
            stockList() {
                return this.list.filter(item => item.stockInNum.indexOf(this.key) > -1)
            },
            stockinNum(){
                const {exploit,exporter,exportNum,totalBoxes} = this.stock;
                const e = ['CON','SP'];
                const exp = ['INLINE','SHCMAN'];
                return `MOR/${e[exploit] || ''}/${exp[exporter] || ''}${exportNum}/${this.shipNumber2}/${totalBoxes}`
            }
        },
        created() {
            this._getStockInList();
            this.getWarehouseList()
        },
        methods: {
            async getWarehouseList(){
                const {status,data} = await getWarehouseList();
                if (status === ERROR_OK ) {
                    this.warehouseList = data
                }
            },
            async getPartDetail(r){
                if(r.partList){
                    return
                }
                const {status,data} = await getStockInRecord(r.id);
                if(status===ERROR_OK) {
                    r.partList = data;
                    const index = this.list.findIndex(item=>item.id===r.id);
                    this.list.splice(index,1,r);
                }

            },
            async submitForm() {
                this.$refs.stock.validate(async valid=>{
                    if (valid) {
                        const {stockInDateStr,id,exploit,exporter,exportNum,shipNumber,totalBoxes,warehouse} = this.stock;
                        const stockInNum = this.stockinNum;
                        let stockInDetails = this.partList.map(item=>{
                            return {
                                partsId:item.id,
                                partsQuantity:item.number
                            }
                        });
                        stockInDetails = JSON.stringify(stockInDetails);
                        const {status,msg} = await stockIn({stockInNum,stockInDateStr,id,stockInDetails,exploit,exporter,exportNum,shipNumber,totalBoxes,warehouse,shipA:this.shipNumber1,shipB:this.shipNumber2});
                        if(status === ERROR_OK) {
                            this.clear();
                            stockInDetails = JSON.parse(stockInDetails).map(item => {
                                return {
                                    partsId:item.partsId,
                                    partsQuantity:-item.partsQuantity
                                }
                            });
                            this.modPartNum(stockInDetails);
                            this._getStockInList();
                            this.dialogVisible = false;
                            this.$notify.success('Stock in Successfully')
                        } else {
                            this.$notify.error(msg)
                        }
                    }
                })


            },
            async saveForm() {
                this.$refs.stock.validate(async valid=>{
                    if(valid) {
                        const {stockInDateStr,id,exploit,exporter,exportNum,shipNumber,totalBoxes,warehouse} = this.stock;
                        const stockInNum = this.stockinNum;
                        let stockInDetails = this.partList.map(item=>{
                            return {
                                partsId:item.id,
                                partsQuantity:item.number
                            }
                        });
                        stockInDetails = JSON.stringify(stockInDetails);
                        const {status,msg} = await saveStockIn({stockInNum,stockInDateStr,id,stockInDetails,exploit,exporter,exportNum,shipNumber,totalBoxes,warehouse,shipA:this.shipNumber1,shipB:this.shipNumber2});
                        if(status === ERROR_OK) {
                            this.clear();
                            stockInDetails = JSON.parse(stockInDetails).map(item => {
                                return {
                                    partsId:item.partsId,
                                    partsQuantity:-item.partsQuantity
                                }
                            });
                            this._getStockInList();
                            this.dialogVisible = false;
                            this.$notify.success('Save Successfully')
                        } else {
                            this.$notify.error(msg)
                        }
                    }
                })

            },
            async fileChange(e){
                const files = e.target.files;
                const file = files[0];
                if(file) {
                    let formData = new FormData();
                    formData.append('exFiles',file);
                    const {status,data,msg} = await upLoadFile(formData);
                    if(status === ERROR_OK) {
                        if(data.data.notExistSparePartsDataBase.length) {
                            this.notExistVisible = true;
                            this.notExist = data.data.notExistSparePartsDataBase
                        }
                        this.partList = data.data.stockInDetail.map(part=>{
                            return {
                                ...part.spareParts,
                                number:part.partsQuantity
                            }
                        })
                    }else{
                        this.$notify.error(msg)
                    }
                }
                this.$nextTick(()=>{
                    this.$refs.file.value = ''
                })
            },
            async showDetail(stock) {
                this.dialogVisible = true;
                this.editable = false;
                const {status,data} = await getStockInDetail(stock.id);
                if(status === ERROR_OK ) {
                    this.stock = stock;
                    this.shipNumber1 = stock.shipA;
                    this.shipNumber2 = stock.shipB;
                    this.partList = data.map(part => {
                        return {
                            ...part.spareParts,
                            number: part.partsQuantity
                        }
                    })
                }
            },
            async _getStockInList() {
                const {status, data} = await getStockInList();
                if (status === ERROR_OK) {
                    this.list = data;
                    this.total = data.length
                }
            },
            async insertDataBase(){
                 this.progress = true;
                for(const item of this.notExist) {
                    const part = {partsNumber:item.partsNum,denomination:item.denomination,designation:item.designation};
                    const {data,status} = await addPart(part);
                    if(status === ERROR_OK) {
                        part.id = data.id;
                        part.quantity = 0;
                        part.salePrice = 0;
                        this.addPart(part);
                        this.current = this.current + 1
                    }
                    if(this.current >= this.notExist.length) {
                        this.progress = false;
                        this.current = 0;
                        this.$notify.success('Insert into database successfully!')
                    }
                }
                 this.progress = false
            },
            clear() {
                this.partList = [];
                this.shipNumber1='';
                this.shipNumber2 = '';
                this.stock = {
                    id:undefined,
                    warehouse:'',
                    stockInNum:'',
                    stockInDateStr:'',
                    stockOutDetails: [],
                    exploit:'',
                    exporter:'',
                    exportNum:'',
                    shipNumber:'',
                    totalBoxes:''
                };
                this.$nextTick(()=>{
                    this.$refs.file.value = ''
                })
            },
            openAdd() {
                this.dialogVisible = true;
                this.clear()
            },
            ...mapActions(['modPartNum']),
            ...mapMutations(['addPart'])
        },
        watch: {
            stockList(list) {
                this.total = list.length
            },
            shipNumber1(shipNumber){
                this.stock.shipNumber = shipNumber+this.shipNumber2
            },
            shipNumber2(shipNumber){
                this.stock.shipNumber = this.shipNumber1 + shipNumber
            }
        },
        components: {
            Crumb, Search, PartItem, DataBase
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";
    .content {
        @include content
    }
    .label{
        width: 90px;
        height: 32px;
        line-height: 32px;
        border-radius: 3px;
        margin-left: 10px;
        text-align: center;
        cursor: pointer;
        font-size: 12px;
        background-color: #409eff;
        color: white;
        display: inline-block;
        vertical-align: top;
    }
    .flex{
        display: flex;
        .flex-content{
            flex: 1;
        }
    }
    .input{
        width: 50%;
    }
</style>